package com.mxpio.erp.quality.service.impl;

import com.mxpio.erp.common.LotStatusUtil;
import com.mxpio.erp.common.enums.*;
import com.mxpio.erp.common.inventory.entity.*;
import com.mxpio.erp.common.inventory.service.LotService;
import com.mxpio.erp.common.jpa.entity.BizNoticeType;
import com.mxpio.erp.common.jpa.model.NoticeLineKey;
import com.mxpio.erp.common.mes.entity.ManufactureWorkOrder;
import com.mxpio.erp.common.mes.entity.ManufactureWorkOrderTask;
import com.mxpio.erp.common.mes.entity.MesScanInfo;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.common.quality.entity.*;
import com.mxpio.erp.common.quality.service.InspectionBillService;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.technology.entity.ItemGroup;
import com.mxpio.erp.common.util.MesScanUtil;
import com.mxpio.erp.common.vo.NoticeClassVo;
import com.mxpio.erp.common.workshop.entity.ManufactureOrderRoute;
import com.mxpio.erp.common.workshop.entity.MoPickingNotice;
import com.mxpio.erp.common.workshop.entity.MoPickingNoticeLine;
import com.mxpio.erp.common.workshop.service.ManufactureOrderRouteService;
import com.mxpio.erp.quality.utils.QualityUtils;
import com.mxpioframework.camunda.CamundaConstant;
import com.mxpioframework.camunda.service.BpmnFlowService;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.impl.CrudType;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.SnRuleService;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class InspectionBillServiceImpl extends BaseServiceImpl<InspectionBill> implements InspectionBillService {
    @Autowired
    private SnRuleService snRuleService;
    @Autowired
    private LotService lotService;
    @Autowired
    private OrderLineService bizOrderLineService;
    @Autowired
    private BpmnFlowService bpmnFlowService;
    @Autowired
    private ManufactureOrderRouteService manufactureOrderRouteService;


    public static final String TEST_RESULT_UNQUALIFIED = "0";
    public static final String TEST_RESULT_QUALIFIED = "1";
    public static final String UD_PROCESS_KEY = "qualityUd";//不良品处理单工作流 key
    public static final Boolean UD_PROCESS_AUTOMATIC = false;//不良品处理单工作流自动发起 241206自动改为手动提交
    @Override
    @Transactional
    public Result<Object> generateSimple(InspectionBill bill) {
        clearHistoricalData(bill.getBizNo());

        String busiType = bill.getBusiType();

        if (StringUtils.equals(InspectionEnums.ISBusiType.Stock.getCode(),busiType)){
            updateInspectionBillStatus(bill);//更新单据中的样本数量和单据检验状态

            String itemCode = bill.getItemCode();//查询物料信息
            Item dbItem = JpaUtil.getOne(Item.class, itemCode);//物料信息
            List<InspectionSchemeChain> chains = JpaUtil.linq(InspectionSchemeChain.class)
                    //.collect("code", InspectionScheme.class,"schemeCode")
                    .equal("busiType","1")//
                    .equal("dataScope","1")
                    .equal("itemCode", itemCode).list();

            int detectNum = 0;
            List<InspectionBillDetect> detectList = new ArrayList<>();
            if (chains.size()>0){//存在物料对应的方案
                InspectionSchemeChain inspectionSchemeChain = chains.get(0);//一个物料只能有一个质检方案
                String schemeCode = inspectionSchemeChain.getSchemeCode();
                InspectionScheme inspectionScheme = JpaUtil.getOne(InspectionScheme.class, schemeCode);
                List<InspectionSchemeLine> inspectionSchemeLines = JpaUtil.linq(InspectionSchemeLine.class)
                        .collect("code", InspectionItem.class, "code")
                        .equal("schemeCode", schemeCode)
                        .list();
                for (InspectionSchemeLine line:inspectionSchemeLines){
                    detectNum++;
                    InspectionBillDetect inspectionBillDetect = new InspectionBillDetect();
                    inspectionBillDetect.setBizNo(bill.getBizNo());
                    inspectionBillDetect.setDetectCode(String.format("%04d",detectNum));
                    inspectionBillDetect.setSort(detectNum);
                    inspectionBillDetect.setDetectSource("1");//1物料、2物料组
                    inspectionBillDetect.setSchemeCode(inspectionScheme.getCode());
                    inspectionBillDetect.setSimpleQuantity(bill.getCheckQuantity());
                    //保存 关联检测项目
                    InspectionItem inspectionItem = line.getInspectionItem();
                    inspectionBillDetect.setInspectionItemCode(inspectionItem.getCode());
                    inspectionBillDetect.setInspectionItemName(inspectionItem.getName());
                    inspectionBillDetect.setInspectionItemClass(inspectionItem.getItemClass());
                    inspectionBillDetect.setInspectionItemType(inspectionItem.getItemType());
                    inspectionBillDetect.setInspectionItemDefectGrade(inspectionItem.getDefectGrade());
                    inspectionBillDetect.setInspectionItemStandard(inspectionItem.getStandard());
                    inspectionBillDetect.setInspectionItemDetectionTool(inspectionItem.getDetectionTool());
                    inspectionBillDetect.setInspectionItemDetectionMethod(inspectionItem.getDetectionMethod());
                    inspectionBillDetect.setInspectionItemTechnicalRequirements(inspectionItem.getTechnicalRequirements());
                    //保存 关联检测方案行
                    inspectionBillDetect.setComparator(line.getComparator());
                    inspectionBillDetect.setTargetValue(line.getTargetValue());
                    inspectionBillDetect.setUnits(line.getUnits());
                    inspectionBillDetect.setMaxValue(line.getMaxValue());
                    inspectionBillDetect.setMinValue(line.getMinValue());

                    //查询 检测项目 参数选项对应默认值
                    List<InspectionItemParam> inspectionItemParams = JpaUtil.linq(InspectionItemParam.class).equal("code", inspectionItem.getCode()).equal("defaultParam", Boolean.TRUE).list();
                    if(!inspectionItemParams.isEmpty()){
                        inspectionBillDetect.setDefaultMeasurement(inspectionItemParams.get(0).getParameter());
                    }

                    JpaUtil.save(inspectionBillDetect);
                    //inspectionBillDetect.setInspectionItem(line.getInspectionItem());
                    //inspectionBillDetect.setInspectionSchemeLine(line);
                    detectList.add(inspectionBillDetect);
                }
            }
            String itemGroupCode = dbItem.getItemGroupCode();
            List<String> schemeCodeList = new ArrayList<>();
            getItemGroupSchemeCode(itemGroupCode,schemeCodeList);//递归查询物料组对应质检方案
            if (schemeCodeList.size()>0){
                for (String schemeCode:schemeCodeList){
                    InspectionScheme inspectionScheme = JpaUtil.getOne(InspectionScheme.class, schemeCode);
                    List<InspectionSchemeLine> inspectionSchemeLines = JpaUtil.linq(InspectionSchemeLine.class)
                            .collect("code", InspectionItem.class, "code")
                            .equal("schemeCode", schemeCode)
                            .list();
                    for (InspectionSchemeLine line:inspectionSchemeLines){
                        detectNum++;
                        InspectionBillDetect inspectionBillDetect = new InspectionBillDetect();
                        inspectionBillDetect.setBizNo(bill.getBizNo());
                        inspectionBillDetect.setDetectCode(String.format("%04d",detectNum));
                        inspectionBillDetect.setSort(detectNum);
                        inspectionBillDetect.setDetectSource("2");//1物料、2物料组
                        inspectionBillDetect.setSchemeCode(inspectionScheme.getCode());
                        inspectionBillDetect.setSimpleQuantity(bill.getCheckQuantity());
                        //保存 关联检测项目
                        InspectionItem inspectionItem = line.getInspectionItem();
                        inspectionBillDetect.setInspectionItemCode(inspectionItem.getCode());
                        inspectionBillDetect.setInspectionItemName(inspectionItem.getName());
                        inspectionBillDetect.setInspectionItemClass(inspectionItem.getItemClass());
                        inspectionBillDetect.setInspectionItemType(inspectionItem.getItemType());
                        inspectionBillDetect.setInspectionItemDefectGrade(inspectionItem.getDefectGrade());
                        inspectionBillDetect.setInspectionItemStandard(inspectionItem.getStandard());
                        inspectionBillDetect.setInspectionItemDetectionTool(inspectionItem.getDetectionTool());
                        inspectionBillDetect.setInspectionItemDetectionMethod(inspectionItem.getDetectionMethod());
                        inspectionBillDetect.setInspectionItemTechnicalRequirements(inspectionItem.getTechnicalRequirements());
                        //保存 关联检测方案行
                        inspectionBillDetect.setComparator(line.getComparator());
                        inspectionBillDetect.setTargetValue(line.getTargetValue());
                        inspectionBillDetect.setUnits(line.getUnits());
                        inspectionBillDetect.setMaxValue(line.getMaxValue());
                        inspectionBillDetect.setMinValue(line.getMinValue());
                        //查询 检测项目 参数选项对应默认值
                        List<InspectionItemParam> inspectionItemParams = JpaUtil.linq(InspectionItemParam.class).equal("code", inspectionItem.getCode()).equal("defaultParam", Boolean.TRUE).list();
                        if(!inspectionItemParams.isEmpty()){
                            inspectionBillDetect.setDefaultMeasurement(inspectionItemParams.get(0).getParameter());
                        }
                        JpaUtil.save(inspectionBillDetect);
                        //inspectionBillDetect.setInspectionItem(line.getInspectionItem());
                        //inspectionBillDetect.setInspectionSchemeLine(line);
                        detectList.add(inspectionBillDetect);
                    }
                }
            }
            List<InspectionBillSimple> simpleList = new ArrayList<>();//样本列表
            Integer scale = dbItem.getScale();
            if (scale!=null && scale!=0){//如果精度不等于零，则只生成一个样本(单位是kg、m这类的物料)
                InspectionBillSimple inspectionBillSimple = new InspectionBillSimple();
                inspectionBillSimple.setBizNo(bill.getBizNo());
                inspectionBillSimple.setSort(1);
                inspectionBillSimple.setSimpleCode(String.format("%04d",1));
                inspectionBillSimple.setDetectQuantity(new BigDecimal(detectList.size()));//检测项数量
                JpaUtil.save(inspectionBillSimple);
                simpleList.add(inspectionBillSimple);//样本
            }else{
                int value = bill.getCheckQuantity().intValue();
                if (value==0){
                    value = 1;//处理前端可能输入小数的情况
                }
                for (int i=0;i<value;i++){
                    InspectionBillSimple inspectionBillSimple = new InspectionBillSimple();
                    inspectionBillSimple.setBizNo(bill.getBizNo());
                    inspectionBillSimple.setSort(i+1);
                    inspectionBillSimple.setSimpleCode(String.format("%04d",i+1));
                    inspectionBillSimple.setDetectQuantity(new BigDecimal(detectList.size()));//检测项数量
                    JpaUtil.save(inspectionBillSimple);
                    simpleList.add(inspectionBillSimple);//样本
                }
            }
            int detailNum = 0;
            List<InspectionBillCheckDetail> details = new ArrayList<>();
            for (InspectionBillSimple simple:simpleList){
                for (InspectionBillDetect detect:detectList){
                    detailNum++;
                    InspectionBillCheckDetail detail = new InspectionBillCheckDetail();
                    detail.setBizNo(bill.getBizNo());
                    detail.setSimpleCode(simple.getSimpleCode());
                    detail.setDetectCode(detect.getDetectCode());
                    detail.setSort(detailNum);

                    //InspectionItem inspectionItem = detect.getInspectionItem();
                    detail.setInspectionItemCode(detect.getInspectionItemCode());
                    detail.setInspectionItemName(detect.getInspectionItemName());
                    detail.setInspectionItemClass(detect.getInspectionItemClass());
                    detail.setInspectionItemType(detect.getInspectionItemType());
                    detail.setInspectionItemDefectGrade(detect.getInspectionItemDefectGrade());
                    detail.setInspectionItemStandard(detect.getInspectionItemStandard());
                    detail.setInspectionItemDetectionTool(detect.getInspectionItemDetectionTool());
                    detail.setInspectionItemDetectionMethod(detect.getInspectionItemDetectionMethod());
                    detail.setInspectionItemTechnicalRequirements(detect.getInspectionItemTechnicalRequirements());

                    //InspectionSchemeLine inspectionSchemeLine = detect.getInspectionSchemeLine();
                    detail.setComparator(detect.getComparator());
                    detail.setTargetValue(detect.getTargetValue());
                    detail.setUnits(detect.getUnits());
                    detail.setMaxValue(detect.getMaxValue());
                    detail.setMinValue(detect.getMinValue());
                    if (StringUtils.isNotBlank(detect.getDefaultMeasurement())){
                        detail.setMeasurement(detect.getDefaultMeasurement());//赋默认值
                    }
                    details.add(detail);
                }
            }
            JpaUtil.save(details);//保存明细
        }else if (StringUtils.equals(InspectionEnums.ISBusiType.Process.getCode(),busiType)){
            updateInspectionBillStatus(bill);//更新单据中的样本数量和单据检验状态

            String itemCode = bill.getItemCode();//查询物料信息
            String schemeCode = bill.getSchemeCode();//质检方案
            Item dbItem = JpaUtil.getOne(Item.class, itemCode);//物料信息
            int detectNum = 0;
            List<InspectionBillDetect> detectList = new ArrayList<>();
            if (StringUtils.isNotBlank(schemeCode)){//存在方案
                InspectionScheme inspectionScheme = JpaUtil.getOne(InspectionScheme.class, schemeCode);
                List<InspectionSchemeLine> inspectionSchemeLines = JpaUtil.linq(InspectionSchemeLine.class)
                        .collect("code", InspectionItem.class, "code")
                        .equal("schemeCode", schemeCode)
                        .list();
                for (InspectionSchemeLine line:inspectionSchemeLines){
                    detectNum++;
                    InspectionBillDetect inspectionBillDetect = new InspectionBillDetect();
                    inspectionBillDetect.setBizNo(bill.getBizNo());
                    inspectionBillDetect.setDetectCode(String.format("%04d",detectNum));
                    inspectionBillDetect.setSort(detectNum);
                    inspectionBillDetect.setDetectSource("1");//1物料、2物料组
                    inspectionBillDetect.setSchemeCode(inspectionScheme.getCode());
                    inspectionBillDetect.setSimpleQuantity(bill.getCheckQuantity());
                    //保存 关联检测项目
                    InspectionItem inspectionItem = line.getInspectionItem();
                    inspectionBillDetect.setInspectionItemCode(inspectionItem.getCode());
                    inspectionBillDetect.setInspectionItemName(inspectionItem.getName());
                    inspectionBillDetect.setInspectionItemClass(inspectionItem.getItemClass());
                    inspectionBillDetect.setInspectionItemType(inspectionItem.getItemType());
                    inspectionBillDetect.setInspectionItemDefectGrade(inspectionItem.getDefectGrade());
                    inspectionBillDetect.setInspectionItemStandard(inspectionItem.getStandard());
                    inspectionBillDetect.setInspectionItemDetectionTool(inspectionItem.getDetectionTool());
                    inspectionBillDetect.setInspectionItemDetectionMethod(inspectionItem.getDetectionMethod());
                    inspectionBillDetect.setInspectionItemTechnicalRequirements(inspectionItem.getTechnicalRequirements());
                    //保存 关联检测方案行
                    inspectionBillDetect.setComparator(line.getComparator());
                    inspectionBillDetect.setTargetValue(line.getTargetValue());
                    inspectionBillDetect.setUnits(line.getUnits());
                    inspectionBillDetect.setMaxValue(line.getMaxValue());
                    inspectionBillDetect.setMinValue(line.getMinValue());

                    //查询 检测项目 参数选项对应默认值
                    List<InspectionItemParam> inspectionItemParams = JpaUtil.linq(InspectionItemParam.class).equal("code", inspectionItem.getCode()).equal("defaultParam", Boolean.TRUE).list();
                    if(!inspectionItemParams.isEmpty()){
                        inspectionBillDetect.setDefaultMeasurement(inspectionItemParams.get(0).getParameter());
                    }
                    JpaUtil.save(inspectionBillDetect);
                    detectList.add(inspectionBillDetect);
                }
            }
            List<InspectionBillSimple> simpleList = new ArrayList<>();//样本列表
            Integer scale = dbItem.getScale();
            if (scale!=null && scale!=0){//如果精度不等于零，则只生成一个样本(单位是kg、m这类的物料)
                InspectionBillSimple inspectionBillSimple = new InspectionBillSimple();
                inspectionBillSimple.setBizNo(bill.getBizNo());
                inspectionBillSimple.setSort(1);
                inspectionBillSimple.setSimpleCode(String.format("%04d",1));
                inspectionBillSimple.setDetectQuantity(new BigDecimal(detectList.size()));//检测项数量
                JpaUtil.save(inspectionBillSimple);
                simpleList.add(inspectionBillSimple);//样本
            }else{
                int value = bill.getCheckQuantity().intValue();
                if (value==0){
                    value = 1;//处理前端可能输入小数的情况
                }
                for (int i=0;i<value;i++){
                    InspectionBillSimple inspectionBillSimple = new InspectionBillSimple();
                    inspectionBillSimple.setBizNo(bill.getBizNo());
                    inspectionBillSimple.setSort(i+1);
                    inspectionBillSimple.setSimpleCode(String.format("%04d",i+1));
                    inspectionBillSimple.setDetectQuantity(new BigDecimal(detectList.size()));//检测项数量
                    JpaUtil.save(inspectionBillSimple);
                    simpleList.add(inspectionBillSimple);//样本
                }
            }
            int detailNum = 0;
            List<InspectionBillCheckDetail> details = new ArrayList<>();
            for (InspectionBillSimple simple:simpleList){
                for (InspectionBillDetect detect:detectList){
                    detailNum++;
                    InspectionBillCheckDetail detail = new InspectionBillCheckDetail();
                    detail.setBizNo(bill.getBizNo());
                    detail.setSimpleCode(simple.getSimpleCode());
                    detail.setDetectCode(detect.getDetectCode());
                    detail.setSort(detailNum);

                    //InspectionItem inspectionItem = detect.getInspectionItem();
                    detail.setInspectionItemCode(detect.getInspectionItemCode());
                    detail.setInspectionItemName(detect.getInspectionItemName());
                    detail.setInspectionItemClass(detect.getInspectionItemClass());
                    detail.setInspectionItemType(detect.getInspectionItemType());
                    detail.setInspectionItemDefectGrade(detect.getInspectionItemDefectGrade());
                    detail.setInspectionItemStandard(detect.getInspectionItemStandard());
                    detail.setInspectionItemDetectionTool(detect.getInspectionItemDetectionTool());
                    detail.setInspectionItemDetectionMethod(detect.getInspectionItemDetectionMethod());
                    detail.setInspectionItemTechnicalRequirements(detect.getInspectionItemTechnicalRequirements());

                    //InspectionSchemeLine inspectionSchemeLine = detect.getInspectionSchemeLine();
                    detail.setComparator(detect.getComparator());
                    detail.setTargetValue(detect.getTargetValue());
                    detail.setUnits(detect.getUnits());
                    detail.setMaxValue(detect.getMaxValue());
                    detail.setMinValue(detect.getMinValue());
                    if (StringUtils.isNotBlank(detect.getDefaultMeasurement())){
                        detail.setMeasurement(detect.getDefaultMeasurement());//赋默认值
                    }
                    details.add(detail);
                }
            }
            JpaUtil.save(details);//保存明细
        }else{
            throw new MBootException("不支持的业务类型");
        }
        return Result.OK();
    }
    private void clearHistoricalData(String bizNo) {//清空历史记录
        JpaUtil.lind(InspectionBillSimple.class).equal("bizNo", bizNo).delete();
        JpaUtil.lind(InspectionBillDetect.class).equal("bizNo", bizNo).delete();
        JpaUtil.lind(InspectionBillCheckDetail.class).equal("bizNo", bizNo).delete();
    }
    private void updateInspectionBillStatus(InspectionBill bill) {
        JpaUtil.linu(InspectionBill.class)
                .set("checkStatus", InspectionEnums.CheckStatus.CHECKING.getCode())
                .set("checkQuantity", bill.getCheckQuantity())
                .equal("bizNo", bill.getBizNo()).update();
    }


    @Transactional
    public void getItemGroupSchemeCode(String itemGroupCode,List<String> schemeCodeList ){
        List<InspectionSchemeChain> chains = JpaUtil.linq(InspectionSchemeChain.class)
                .equal("busiType","1")//入库
                .equal("dataScope","2")
                .equal("itemCode", itemGroupCode).list();
        if (chains.size()>0){
            InspectionSchemeChain inspectionSchemeChain = chains.get(0);
            String schemeCode = inspectionSchemeChain.getSchemeCode();
            if (!schemeCodeList.contains(schemeCode)){
                schemeCodeList.add(schemeCode);
            }
        }
        ItemGroup itemGroup = JpaUtil.getOne(ItemGroup.class, itemGroupCode);
        String faGroupCode = itemGroup.getFaGroupCode();
        if (StringUtils.isNotBlank(faGroupCode)){
            getItemGroupSchemeCode(faGroupCode,schemeCodeList);
        }
    }

    @Override
    @Transactional
    public Result<Object> judge(InspectionBill bill, String testResult) {
        Long checkedCount = JpaUtil.linq(InspectionBillCheckDetail.class).equal("bizNo", bill.getBizNo()).isNull("testResult").count();
        if (checkedCount>0){
            return Result.error("存在未维护实测值的质检明细，无法执行判定");
        }
        String busiType = bill.getBusiType();
        if (StringUtils.equals(InspectionEnums.ISBusiType.Stock.getCode(),busiType)){
            //入库质检
            //关联上游验收单
            String originNoticeNo = bill.getOriginNoticeNo();
            String originBizType = bill.getOriginBizType();
            String originNoticeLineNo = bill.getOriginNoticeLineNo();
            NoticeLineKey lineKey = new NoticeLineKey();
            lineKey.setNoticeNo(originNoticeNo);
            lineKey.setLineNo(originNoticeLineNo);

        /*List<BizNoticeType> bizNoticeTypes = JpaUtil.linq(BizNoticeType.class).list();
        Map<String, BizNoticeType> typesMap = JpaUtil.index(bizNoticeTypes);*/
            List<InvFlow> unqualifiedFlowList = new ArrayList<>();
            boolean testUnqualified = false;
            boolean testQualifiedWithDefect = false;//结论合格但存在不合格数量
            if (originBizType.equals(InspectionEnums.OriginBizType.PURCH.getCode())){//采购验收 InQualityOrder
                InQualityOrder inQualityOrder = JpaUtil.getOne(InQualityOrder.class, originNoticeNo);

                InQualityOrderLine inQualityOrderLine = JpaUtil.getOne(InQualityOrderLine.class, lineKey);

                inQualityOrderLine.setAcceptanceBy(bill.getCreateBy());
                inQualityOrderLine.setAcceptanceTime(new Date());
                inQualityOrderLine.setCheckQuantity(bill.getCheckQuantity());
                inQualityOrderLine.setUnqualifiedQuantity(bill.getUnqualifiedQuantity());
                //inQualityOrderLine.setConcessionQuantity(bill.getConcessionQuantity());
                inQualityOrderLine.setCheckResult(testResult);
                JpaUtil.update(inQualityOrderLine);//回写 验收单明细行 对应字段
                if (StringUtils.equals(testResult, TEST_RESULT_QUALIFIED)){//整单合格

                    String lotNo = null;
                    BizNoticeType bizNoticeType = JpaUtil.getOne(BizNoticeType.class, "Q01");
                    StringBuffer expression = new StringBuffer(bizNoticeType.getTypePrefix());
                    for(int i=0 ;i < bizNoticeType.getTypeSize(); i++){
                        expression.append("#");
                    }
                    lotNo = snRuleService.execute(expression.toString(), null).toString()+ "-" + originNoticeLineNo;
                    if (bill.getReceiveQuantity()!=null&&bill.getReceiveQuantity().compareTo(BigDecimal.ZERO)!=0){
                        //接收数量生成对应仓单
                        WarehouseOrder inWo = new WarehouseOrder();
                        inWo.setAccessType(inQualityOrder.getAccessType());//入库
                        inWo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                        inWo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        inWo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                        inWo.setOrderDate(new Date());
                        inWo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        inWo.setWhCode(inQualityOrder.getWhCode());
                        inWo.setWoType(inQualityOrder.getPickingType());
                        inWo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                        JpaUtil.save(inWo);

                        WarehouseOrderLine inWoLine = new WarehouseOrderLine();
                        inWoLine.setWhCode(inWo.getWhCode());
                        inWoLine.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                        inWoLine.setItemCode(item.getItemCode());
                        inWoLine.setItemGroupCode(item.getItemGroupCode());
                        inWoLine.setItemName(item.getItemName());
                        inWoLine.setItemSpec(item.getItemSpec());
                        inWoLine.setUnitCode(item.getUnitCode());
                        inWoLine.setDrawingNo(item.getDrawingNo());
                        inWoLine.setQuantity(bill.getReceiveQuantity());//接收数量
                        inWoLine.setBizNo(inWo.getBizNo());
                        inWoLine.setLineNo("1");
                        inWoLine.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        inWoLine.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                        inWoLine.setSort("1");

                        //生成p批次逻辑：
                        Lot lot = new Lot();
                        lot.setLotNo(lotNo);
                        lot.setLotStatus(LotStatusUtil.toBinaryString("0"));//默认16位0
                        lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());
                        lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                        JpaUtil.save(lot);
                        inWoLine.setLotNo(lotNo);
                        inWoLine.setSubLotIndex(lot.getSubLotIndex());
                        inWoLine.setOriginNoticeNo(originNoticeNo);
                        inWoLine.setOriginNoticeLineNo(originNoticeLineNo);
                        JpaUtil.save(inWoLine);

                        //处理jit送货计划相关
                        if (StringUtils.isNotBlank(inQualityOrder.getFeedPlanNoticeNo())){
                            //回写领、补料通知单行数量，以及批次
                            FeedPlanNotice feedPlanNotice = JpaUtil.getOne(FeedPlanNotice.class, inQualityOrder.getFeedPlanNoticeNo());
                            MoPickingNotice pickingNotice = JpaUtil.linq(MoPickingNotice.class).collect("noticeNo", MoPickingNoticeLine.class, "noticeNo")
                                    .equal("noticeNo", feedPlanNotice.getSourcePickingNoticeNo()).findOne();
                            pickingNotice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode());//确认状态

                            List<MoPickingNoticeLine> moPickingNoticeLines = pickingNotice.getMoPickingNoticeLines();//jit对应的领补料通知单都是单行明细
                            moPickingNoticeLines.get(0).setQuantity(inWoLine.getQuantity());//确认数量
                            moPickingNoticeLines.get(0).setLotNo(inWoLine.getLotNo());
                            moPickingNoticeLines.get(0).setSubLotIndex(inWoLine.getSubLotIndex());
                            moPickingNoticeLines.get(0).setCrudType(CrudType.UPDATE);
                            JpaUtil.update(pickingNotice);//更新pickingNotice及明细行

                            boolean automatic = false;//自动化执行标志，后续改为全局变量控制
                            if (automatic) {//自动入和自动出
                                //1.首先入库仓单需要自动执行
                                //自动执行，生成流水
                                InvFlow inFlow = new InvFlow();
                                inFlow.setAccessType(inWo.getAccessType());
                                inFlow.setItemCode(inWoLine.getItemCode());
                                inFlow.setWhCode(inWo.getWhCode());
                                inFlow.setQuantity(inWoLine.getQuantity());
                                inFlow.setMemo(inWo.getMemo());
                                inFlow.setOriginBizNo(inWo.getOriginBizNo());
                                inFlow.setOriginBizType(inWo.getOriginBizType());
                                inFlow.setOriginBizLineNo(inWoLine.getOriginBizLineNo());
                                inFlow.setWoBizNo(inWo.getBizNo());
                                inFlow.setWoBizType(inWo.getWoType());
                                inFlow.setWoBizLineNo(inWoLine.getLineNo());
                                inFlow.setLotNo(inWoLine.getLotNo());
                                inFlow.setSubLotIndex(inWoLine.getSubLotIndex());//增加子批索引
                                JpaUtil.save(inFlow);
                                //更新仓单状态
                                inWo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                                inWo.setExecuteTime(new Date());
                                inWo.setExecutor("8888");//自动化助手，默认指定用户
                                JpaUtil.update(inWo);

                                //自动出生成仓单，且自动执行
                                WarehouseOrder outWo = new WarehouseOrder();
                                outWo.setAccessType(pickingNotice.getAccessType());
                                outWo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                                outWo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                                outWo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                                outWo.setOrderDate(new Date());
                                outWo.setOriginBizNo(pickingNotice.getBizOrderNo());
                                outWo.setWhCode(pickingNotice.getWhCode());
                                outWo.setWoType(pickingNotice.getPickingType());
                                outWo.setOriginNoticeNo(pickingNotice.getNoticeNo());//关联noticeno字段
                                outWo.setExecuteTime(new Date());
                                outWo.setExecutor("8888");//自动化助手，默认指定用户
                                JpaUtil.save(outWo);

                                WarehouseOrderLine outWoLine = new WarehouseOrderLine();
                                outWoLine.setWhCode(outWo.getWhCode());
                                outWoLine.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                                outWoLine.setItemCode(inFlow.getItemCode());
                                outWoLine.setItemGroupCode(inWoLine.getItemGroupCode());
                                outWoLine.setItemName(inWoLine.getItemName());
                                outWoLine.setItemSpec(inWoLine.getItemSpec());
                                outWoLine.setUnitCode(inWoLine.getUnitCode());
                                outWoLine.setDrawingNo(inWoLine.getDrawingNo());
                                outWoLine.setQuantity(inFlow.getQuantity());
                                outWoLine.setBizNo(outWo.getBizNo());
                                outWoLine.setLineNo("1");
                                outWoLine.setOriginBizNo(moPickingNoticeLines.get(0).getOriginBizNo());
                                outWoLine.setOriginBizLineNo(moPickingNoticeLines.get(0).getOriginBizLineNo());
                                outWoLine.setLotNo(inFlow.getLotNo());
                                outWoLine.setSubLotIndex(inFlow.getSubLotIndex());
                                outWoLine.setOriginNoticeNo(pickingNotice.getNoticeNo());
                                outWoLine.setOriginNoticeLineNo(moPickingNoticeLines.get(0).getLineNo());
                                JpaUtil.save(outWoLine);
                                //自动执行，生成出流水
                                InvFlow outFlow = new InvFlow();
                                outFlow.setAccessType(outWo.getAccessType());
                                outFlow.setItemCode(outWoLine.getItemCode());
                                outFlow.setWhCode(outWo.getWhCode());
                                outFlow.setQuantity(outWoLine.getQuantity());
                                outFlow.setMemo(outWo.getMemo());
                                outFlow.setOriginBizNo(outWo.getOriginBizNo());
                                outFlow.setOriginBizType(outWo.getOriginBizType());
                                outFlow.setOriginBizLineNo(outWoLine.getOriginBizLineNo());
                                outFlow.setWoBizNo(outWo.getBizNo());
                                outFlow.setWoBizType(outWo.getWoType());
                                outFlow.setWoBizLineNo(outWoLine.getLineNo());
                                outFlow.setLotNo(outWoLine.getLotNo());
                                outFlow.setSubLotIndex(outWoLine.getSubLotIndex());//增加子批索引
                                JpaUtil.save(outFlow);
                            }else{
                                //生产的入库仓单需要人工来确认
                                //生成待执行的出库仓单
                                WarehouseOrder outWo = new WarehouseOrder();
                                outWo.setAccessType(pickingNotice.getAccessType());
                                outWo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                                outWo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                                outWo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                                outWo.setOrderDate(new Date());
                                outWo.setOriginBizNo(pickingNotice.getBizOrderNo());
                                outWo.setWhCode(pickingNotice.getWhCode());
                                outWo.setWoType(pickingNotice.getPickingType());
                                outWo.setOriginNoticeNo(pickingNotice.getNoticeNo());//关联noticeno字段
                                JpaUtil.save(outWo);

                                WarehouseOrderLine outWoLine = new WarehouseOrderLine();
                                outWoLine.setWhCode(outWo.getWhCode());
                                outWoLine.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                                outWoLine.setItemCode(inWoLine.getItemCode());
                                outWoLine.setItemGroupCode(inWoLine.getItemGroupCode());
                                outWoLine.setItemName(inWoLine.getItemName());
                                outWoLine.setItemSpec(inWoLine.getItemSpec());
                                outWoLine.setUnitCode(inWoLine.getUnitCode());
                                outWoLine.setDrawingNo(inWoLine.getDrawingNo());
                                outWoLine.setQuantity(inWoLine.getQuantity());
                                outWoLine.setBizNo(outWo.getBizNo());
                                outWoLine.setLineNo("1");
                                outWoLine.setOriginBizNo(moPickingNoticeLines.get(0).getOriginBizNo());
                                outWoLine.setOriginBizLineNo(moPickingNoticeLines.get(0).getOriginBizLineNo());
                                outWoLine.setLotNo(inWoLine.getLotNo());
                                outWoLine.setSubLotIndex(inWoLine.getSubLotIndex());
                                outWoLine.setOriginNoticeNo(pickingNotice.getNoticeNo());
                                outWoLine.setOriginNoticeLineNo(moPickingNoticeLines.get(0).getLineNo());
                                JpaUtil.save(outWoLine);
                            }
                        }
                    }

                    if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                        //如果不合格数量等于报检数量时，需要把对应的领料通知单 拒绝掉
                        if (bill.getUnqualifiedQuantity().compareTo(bill.getQuantity())==0&&StringUtils.isNotBlank(inQualityOrder.getFeedPlanNoticeNo())){
                            FeedPlanNotice feedPlanNotice = JpaUtil.getOne(FeedPlanNotice.class, inQualityOrder.getFeedPlanNoticeNo());
                            MoPickingNotice pickingNotice = JpaUtil.linq(MoPickingNotice.class).collect("noticeNo", MoPickingNoticeLine.class, "noticeNo")
                                    .equal("noticeNo", feedPlanNotice.getSourcePickingNoticeNo()).findOne();
                            pickingNotice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.REJECT.getStatusCode());//确认状态
                            JpaUtil.update(pickingNotice);
                        }

                        // 20240119 wupp 和王震沟通，采购质检的不合格部分，不再产生不合格的入库仓单及流水
                /*//不合格数量 生成对应仓单 并自动执行
                WarehouseOrder wo = new WarehouseOrder();
                wo.setAccessType(inQualityOrder.getAccessType());//入库
                wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                wo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                wo.setOrderDate(new Date());
                wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                wo.setWhCode("WH0005");// 仓单仓库 指定为不合格品仓：WH0005
                wo.setWoType(inQualityOrder.getPickingType());
                wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                wo.setExecutor("8888");//自动化助手，默认指定用户
                wo.setExecuteTime(new Date());
                JpaUtil.save(wo);

                WarehouseOrderLine line = new WarehouseOrderLine();
                line.setWhCode(wo.getWhCode());
                line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                line.setItemCode(item.getItemCode());
                line.setItemGroupCode(item.getItemGroupCode());
                line.setItemName(item.getItemName());
                line.setItemSpec(item.getItemSpec());
                line.setUnitCode(item.getUnitCode());
                line.setDrawingNo(item.getDrawingNo());
                line.setQuantity(bill.getUnqualifiedQuantity());//不合格数量
                line.setBizNo(wo.getBizNo());
                line.setLineNo("1");
                line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                line.setSort("1");

                Lot lot = new Lot();
                lot.setLotNo(lotNo);
                lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());//索引
                String binaryString = LotStatusUtil.toBinaryString("0");//默认正常
                lot.setLotStatus(LotStatusUtil.switchBinaryByIndex(binaryString,InspectionEnums.LotStatusBitIndex.IB15.getIndex()));
                lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                JpaUtil.save(lot);

                line.setLotNo(lot.getLotNo());
                line.setSubLotIndex(lot.getSubLotIndex());
                line.setOriginNoticeNo(originNoticeNo);
                line.setOriginNoticeLineNo(originNoticeLineNo);
                JpaUtil.save(line);

                //自动执行，生成流水
                InvFlow inFlow = new InvFlow();
                inFlow.setAccessType(wo.getAccessType());
                inFlow.setItemCode(line.getItemCode());
                inFlow.setWhCode(wo.getWhCode());
                inFlow.setQuantity(line.getQuantity());
                inFlow.setMemo(wo.getMemo());
                inFlow.setOriginBizNo(wo.getOriginBizNo());
                inFlow.setOriginBizType(wo.getOriginBizType());
                inFlow.setOriginBizLineNo(line.getOriginBizLineNo());
                inFlow.setWoBizNo(wo.getBizNo());
                inFlow.setWoBizType(wo.getWoType());
                inFlow.setWoBizLineNo(line.getLineNo());
                inFlow.setLotNo(line.getLotNo());
                inFlow.setSubLotIndex(line.getSubLotIndex());//增加子批索引
                JpaUtil.save(inFlow);
                unqualifiedFlowList.add(inFlow);//不合格拆批明细

                //jit物料生成的不合格批次，自动创建退货通知单。采购订单的不合格退货，按正常的退货流程处理
                if (StringUtils.isNotBlank(inQualityOrder.getFeedPlanNoticeNo())){
                    //同时生成不合格退货通知单
                    String feedPlanNoticeNo = inQualityOrder.getFeedPlanNoticeNo();
                    RejectNotice rejectNotice = new RejectNotice();
                    String rejectType = "";//值对应通知单退货类型字典值
                    if (StringUtils.equals(lot.getLotStatus(), LotStatusUtil.toBinaryString("0"))){
                        rejectType = "0";//合格品退货
                    }else{
                        rejectType = "1";//不合格品退货
                    }
                    rejectNotice.setRejectType(rejectType);
                    *//*if (StringUtils.isNotBlank(feedPlanNoticeNo)){//由jit入产生的质检单
                        rejectNotice.setBizOrderNo(feedPlanNoticeNo);
                    }else{
                        rejectNotice.setBizOrderNo(wo.getOriginBizNo());
                    }*//*
                    rejectNotice.setBizOrderNo(wo.getOriginBizNo());
                    rejectNotice.setNoticeDate(new Date());
                    rejectNotice.setWhCode(wo.getWhCode());
                    rejectNotice.setAccessType(OrderEnums.AccessType.OUT.getCode());
                    rejectNotice.setPickingType(NoticeStatusEnums.NoticeType.PO_DEF_OUT.getCode());
                    rejectNotice.setNoticeStatus(NoticeStatusEnums.NoticeStatus.CREATE.getStatusCode());
                    JpaUtil.save(rejectNotice);

                    NoticeLine noticeLine = new RejectNoticeLine();
                    noticeLine.setOriginBizLineNo(line.getOriginBizLineNo());
                    noticeLine.setOriginBizNo(line.getOriginBizNo());
                    noticeLine.setItemCode(line.getItemCode());
                    noticeLine.setNoticeNo(rejectNotice.getNoticeNo());
                    noticeLine.setQuantity(line.getQuantity());
                    noticeLine.setLotNo(line.getLotNo());
                    noticeLine.setSubLotIndex(line.getSubLotIndex());
                    noticeLine.setLineNo("1");
                    noticeLine.setItemName(line.getItemName());
                    noticeLine.setItemSpec(line.getItemSpec());
                    noticeLine.setUnitCode(line.getUnitCode());
                    noticeLine.setDrawingNo(line.getDrawingNo());
                    JpaUtil.save(noticeLine);
                }*/
                    }
                }else{//质检结论不合格，产生对应的不良品处理单
                    testUnqualified = true;//检验不合格
                }
            }else if (originBizType.equals(InspectionEnums.OriginBizType.MANF.getCode())){//生产验收 MoInQualityOrder
                MoInQualityOrder inQualityOrder = JpaUtil.getOne(MoInQualityOrder.class, originNoticeNo);
                MoInQualityOrderLine inQualityOrderLine = JpaUtil.getOne(MoInQualityOrderLine.class, lineKey);

                inQualityOrderLine.setAcceptanceBy(bill.getCreateBy());
                inQualityOrderLine.setAcceptanceTime(new Date());
                inQualityOrderLine.setCheckQuantity(bill.getCheckQuantity());
                inQualityOrderLine.setUnqualifiedQuantity(bill.getUnqualifiedQuantity());
                inQualityOrderLine.setConcessionQuantity(bill.getConcessionQuantity());
                inQualityOrderLine.setCheckResult(testResult);
                JpaUtil.update(inQualityOrderLine);//回写 验收单明细行 对应字段
                if (StringUtils.equals(testResult, TEST_RESULT_QUALIFIED)) {//整单合格
                    String lotNo = null;
                    BizNoticeType bizNoticeType = JpaUtil.getOne(BizNoticeType.class, "Q01");
                    StringBuffer expression = new StringBuffer(bizNoticeType.getTypePrefix());
                    for(int i=0 ;i < bizNoticeType.getTypeSize(); i++){
                        expression.append("#");
                    }
                    if (bill.getReceiveQuantity()!=null&&bill.getReceiveQuantity().compareTo(BigDecimal.ZERO)!=0){
                        lotNo = snRuleService.execute(expression.toString(), null).toString()+ "-" + originNoticeLineNo;
                        //接收数量生成对应仓单
                        WarehouseOrder wo = new WarehouseOrder();
                        wo.setAccessType(inQualityOrder.getAccessType());//入库
                        wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                        wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        wo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                        wo.setOrderDate(new Date());
                        wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        wo.setWhCode(inQualityOrder.getWhCode());
                        wo.setWoType(inQualityOrder.getPickingType());
                        wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                        JpaUtil.save(wo);

                        WarehouseOrderLine line = new WarehouseOrderLine();
                        line.setWhCode(wo.getWhCode());
                        line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                        line.setItemCode(item.getItemCode());
                        line.setItemGroupCode(item.getItemGroupCode());
                        line.setItemName(item.getItemName());
                        line.setItemSpec(item.getItemSpec());
                        line.setUnitCode(item.getUnitCode());
                        line.setDrawingNo(item.getDrawingNo());
                        line.setQuantity(bill.getReceiveQuantity());//接收数量
                        line.setBizNo(wo.getBizNo());
                        line.setLineNo("1");
                        line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                        line.setSort("1");

                        //生成p批次逻辑：
                        Lot lot = new Lot();
                        lot.setLotNo(lotNo);
                        lot.setLotStatus(LotStatusUtil.toBinaryString("0"));
                        lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());
                        lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                        JpaUtil.save(lot);
                        line.setLotNo(lotNo);
                        line.setSubLotIndex(lot.getSubLotIndex());

                        line.setOriginNoticeNo(originNoticeNo);
                        line.setOriginNoticeLineNo(originNoticeLineNo);
                        JpaUtil.save(line);
                    }
                    if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                        testQualifiedWithDefect = true;//
                    }
                /*if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                    //判退数量 生成对应仓单，自动执行
                    WarehouseOrder wo = new WarehouseOrder();
                    wo.setAccessType(inQualityOrder.getAccessType());//入库
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    wo.setWhCode("WH0005");// 仓单仓库 指定为不合格品仓：WH0005
                    wo.setWoType(inQualityOrder.getPickingType());
                    wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                    //wo.setExecutor(SecurityUtils.getLoginUsername());
                    wo.setExecutor("8888");//自动化助手，默认指定用户
                    wo.setExecuteTime(new Date());
                    JpaUtil.save(wo);

                    WarehouseOrderLine line = new WarehouseOrderLine();
                    line.setWhCode(wo.getWhCode());
                    line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                    line.setItemCode(item.getItemCode());
                    line.setItemGroupCode(item.getItemGroupCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                    line.setQuantity(bill.getUnqualifiedQuantity());//不合格数量
                    line.setBizNo(wo.getBizNo());
                    line.setLineNo("1");
                    line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                    //记录新批次号
                    Lot lot = new Lot();
                    lot.setLotNo(lotNo);
                    lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());//索引
                    String binaryString = LotStatusUtil.toBinaryString("0");//默认正常
                    lot.setLotStatus(LotStatusUtil.switchBinaryByIndex(binaryString,InspectionEnums.LotStatusBitIndex.IB15.getIndex()));
                    lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                    JpaUtil.save(lot);

                    line.setSort("1");
                    line.setLotNo(lot.getLotNo());
                    line.setSubLotIndex(lot.getSubLotIndex());
                    line.setOriginNoticeNo(originNoticeNo);
                    line.setOriginNoticeLineNo(originNoticeLineNo);
                    JpaUtil.save(line);

                    //自动执行，生成流水
                    InvFlow inFlow = new InvFlow();
                    inFlow.setAccessType(wo.getAccessType());
                    inFlow.setItemCode(line.getItemCode());
                    inFlow.setWhCode(wo.getWhCode());
                    inFlow.setQuantity(line.getQuantity());
                    inFlow.setMemo(wo.getMemo());
                    inFlow.setOriginBizNo(wo.getOriginBizNo());
                    inFlow.setOriginBizType(wo.getOriginBizType());
                    inFlow.setOriginBizLineNo(line.getOriginBizLineNo());
                    inFlow.setWoBizNo(wo.getBizNo());
                    inFlow.setWoBizType(wo.getWoType());
                    inFlow.setWoBizLineNo(line.getLineNo());
                    inFlow.setLotNo(line.getLotNo());
                    inFlow.setSubLotIndex(line.getSubLotIndex());//增加子批索引
                    JpaUtil.save(inFlow);
                    unqualifiedFlowList.add(inFlow);//不合格拆批明细
                }*/
                }else{
                    testUnqualified = true;//检验不合格
                }
            }else if (originBizType.equals(InspectionEnums.OriginBizType.OUTS.getCode())){//委外验收 OoInQualityOrder
                OoInQualityOrder inQualityOrder = JpaUtil.getOne(OoInQualityOrder.class, originNoticeNo);
                OoInQualityOrderLine inQualityOrderLine = JpaUtil.getOne(OoInQualityOrderLine.class, lineKey);

                inQualityOrderLine.setAcceptanceBy(bill.getCreateBy());
                inQualityOrderLine.setAcceptanceTime(new Date());
                inQualityOrderLine.setCheckQuantity(bill.getCheckQuantity());
                inQualityOrderLine.setUnqualifiedQuantity(bill.getUnqualifiedQuantity());
                inQualityOrderLine.setConcessionQuantity(bill.getConcessionQuantity());
                inQualityOrderLine.setCheckResult(testResult);
                JpaUtil.update(inQualityOrderLine);//回写 验收单明细行 对应字段
                if (StringUtils.equals(testResult, TEST_RESULT_QUALIFIED)) {
                    String lotNo = null;
                    BizNoticeType bizNoticeType = JpaUtil.getOne(BizNoticeType.class, "Q01");
                    StringBuffer expression = new StringBuffer(bizNoticeType.getTypePrefix());
                    for(int i=0 ;i < bizNoticeType.getTypeSize(); i++){
                        expression.append("#");
                    }
                    lotNo = snRuleService.execute(expression.toString(), null).toString()+ "-" + originNoticeLineNo;
                    if (bill.getReceiveQuantity()!=null&&bill.getReceiveQuantity().compareTo(BigDecimal.ZERO)!=0){
                        //接收数量生成对应仓单
                        WarehouseOrder wo = new WarehouseOrder();
                        wo.setAccessType(inQualityOrder.getAccessType());//入库
                        wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                        wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        wo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                        wo.setOrderDate(new Date());
                        wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        wo.setWhCode(inQualityOrder.getWhCode());
                        wo.setWoType(inQualityOrder.getPickingType());
                        wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                        JpaUtil.save(wo);

                        WarehouseOrderLine line = new WarehouseOrderLine();
                        line.setWhCode(wo.getWhCode());
                        line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                        line.setItemCode(item.getItemCode());
                        line.setItemGroupCode(item.getItemGroupCode());
                        line.setItemName(item.getItemName());
                        line.setItemSpec(item.getItemSpec());
                        line.setUnitCode(item.getUnitCode());
                        line.setDrawingNo(item.getDrawingNo());
                        line.setQuantity(bill.getReceiveQuantity());//接收数量
                        line.setBizNo(wo.getBizNo());
                        line.setLineNo("1");
                        line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                        line.setSort("1");

                        //生成p批次逻辑：
                        Lot lot = new Lot();
                        lot.setLotNo(lotNo);
                        lot.setLotStatus(LotStatusUtil.toBinaryString("0"));
                        lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());
                        lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                        JpaUtil.save(lot);
                        line.setLotNo(lot.getLotNo());
                        line.setSubLotIndex(lot.getSubLotIndex());
                        line.setOriginNoticeNo(originNoticeNo);
                        line.setOriginNoticeLineNo(originNoticeLineNo);
                        JpaUtil.save(line);
                    }

                    if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                        testQualifiedWithDefect = true;
                    /*//判退数量 生成对应仓单，自动执行
                    WarehouseOrder wo = new WarehouseOrder();
                    wo.setAccessType(inQualityOrder.getAccessType());//入库
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    wo.setWhCode("WH0005");// 仓单仓库 指定为不合格品仓：WH0005
                    wo.setWoType(inQualityOrder.getPickingType());
                    wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                    //wo.setExecutor(SecurityUtils.getLoginUsername());
                    wo.setExecutor("8888");//自动化助手，默认指定用户
                    wo.setExecuteTime(new Date());
                    JpaUtil.save(wo);

                    WarehouseOrderLine line = new WarehouseOrderLine();
                    line.setWhCode(wo.getWhCode());
                    line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                    line.setItemCode(item.getItemCode());
                    line.setItemGroupCode(item.getItemGroupCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                    line.setQuantity(bill.getUnqualifiedQuantity());//不合格数量
                    line.setBizNo(wo.getBizNo());
                    line.setLineNo("1");
                    line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                    line.setSort("1");

                    //记录新批次号
                    Lot lot = new Lot();
                    lot.setLotNo(lotNo);
                    lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());//索引
                    String binaryString = LotStatusUtil.toBinaryString("0");//默认正常
                    lot.setLotStatus(LotStatusUtil.switchBinaryByIndex(binaryString,InspectionEnums.LotStatusBitIndex.IB15.getIndex()));
                    lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                    JpaUtil.save(lot);

                    line.setLotNo(lot.getLotNo());
                    line.setSubLotIndex(lot.getSubLotIndex());
                    line.setOriginNoticeNo(originNoticeNo);
                    line.setOriginNoticeLineNo(originNoticeLineNo);
                    JpaUtil.save(line);

                    //自动执行，生成流水
                    InvFlow inFlow = new InvFlow();
                    inFlow.setAccessType(wo.getAccessType());
                    inFlow.setItemCode(line.getItemCode());
                    inFlow.setWhCode(wo.getWhCode());
                    inFlow.setQuantity(line.getQuantity());
                    inFlow.setMemo(wo.getMemo());
                    inFlow.setOriginBizNo(wo.getOriginBizNo());
                    inFlow.setOriginBizType(wo.getOriginBizType());
                    inFlow.setOriginBizLineNo(line.getOriginBizLineNo());
                    inFlow.setWoBizNo(wo.getBizNo());
                    inFlow.setWoBizType(wo.getWoType());
                    inFlow.setWoBizLineNo(line.getLineNo());
                    inFlow.setLotNo(line.getLotNo());
                    inFlow.setSubLotIndex(line.getSubLotIndex());//增加子批索引
                    JpaUtil.save(inFlow);
                    unqualifiedFlowList.add(inFlow);//不合格拆批明细*/
                    }
                }else{
                    testUnqualified = true;
                }
            }else if (originBizType.equals(InspectionEnums.OriginBizType.INVENTORY.getCode())){//库存质检验收 MoInQualityOrder
                InventoryQualityOrder inventoryQualityOrder = JpaUtil.getOne(InventoryQualityOrder.class, originNoticeNo);
                InventoryQualityOrderLine inventoryQualityOrderLine = JpaUtil.getOne(InventoryQualityOrderLine.class, lineKey);

                inventoryQualityOrderLine.setAcceptanceBy(bill.getCreateBy());
                inventoryQualityOrderLine.setAcceptanceTime(new Date());
                inventoryQualityOrderLine.setCheckQuantity(bill.getCheckQuantity());
                inventoryQualityOrderLine.setUnqualifiedQuantity(bill.getUnqualifiedQuantity());
                inventoryQualityOrderLine.setConcessionQuantity(bill.getConcessionQuantity());
                inventoryQualityOrderLine.setCheckResult(testResult);
                JpaUtil.update(inventoryQualityOrderLine);//回写 验收单明细行 对应字段


                if (StringUtils.equals(testResult, TEST_RESULT_QUALIFIED)) {
                    String lotNo = inventoryQualityOrderLine.getLotNo();
                    Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                    if (bill.getReceiveQuantity()!=null&&bill.getReceiveQuantity().compareTo(BigDecimal.ZERO)!=0){
                        //接收数量生成对应仓单
                        WarehouseOrder wo = new WarehouseOrder();
                        wo.setAccessType(inventoryQualityOrder.getAccessType());//入库
                        wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                        wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        wo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                        wo.setOrderDate(new Date());
                        wo.setOriginBizNo(inventoryQualityOrderLine.getOriginBizNo());
                        wo.setWhCode(item.getDefaultWhCode());//取物料的默认仓库
                        wo.setWoType(inventoryQualityOrder.getPickingType());
                        wo.setOriginNoticeNo(inventoryQualityOrder.getNoticeNo());//关联noticeno字段
                        JpaUtil.save(wo);

                        WarehouseOrderLine line = new WarehouseOrderLine();
                        line.setWhCode(wo.getWhCode());
                        line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        line.setItemCode(item.getItemCode());
                        line.setItemGroupCode(item.getItemGroupCode());
                        line.setItemName(item.getItemName());
                        line.setItemSpec(item.getItemSpec());
                        line.setUnitCode(item.getUnitCode());
                        line.setDrawingNo(item.getDrawingNo());
                        line.setQuantity(bill.getReceiveQuantity());//接收数量
                        line.setBizNo(wo.getBizNo());
                        line.setLineNo("1");
                        line.setOriginBizNo(inventoryQualityOrderLine.getOriginBizNo());
                        line.setOriginBizLineNo(inventoryQualityOrderLine.getOriginBizLineNo());
                        line.setSort("1");

                        //生成p批次逻辑：
                        // 此处生成新批次的原因在于批属性质检单单号字段记录质检单单号，批次库存视图会根据批次号关联质检单单号，获取质检情况数据，防止一个（批次+索引）对应多个质检单的情况
                        Lot lot = new Lot();
                        lot.setLotNo(lotNo);
                        lot.setLotStatus(LotStatusUtil.toBinaryString("0"));
                        lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());
                        lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                        JpaUtil.save(lot);
                        line.setLotNo(lotNo);
                        line.setSubLotIndex(lot.getSubLotIndex());

                        line.setOriginNoticeNo(originNoticeNo);
                        line.setOriginNoticeLineNo(originNoticeLineNo);
                        JpaUtil.save(line);
                    }

                    if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                        testQualifiedWithDefect = true;
                    /*//判退数量 生成对应仓单，自动执行
                    WarehouseOrder wo = new WarehouseOrder();
                    wo.setAccessType(inventoryQualityOrder.getAccessType());//入库
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(inventoryQualityOrderLine.getOriginBizNo());
                    wo.setWhCode("WH0005");// 仓单仓库 指定为不合格品仓：WH0005
                    wo.setWoType(inventoryQualityOrder.getPickingType());
                    wo.setOriginNoticeNo(inventoryQualityOrder.getNoticeNo());//关联noticeno字段
                    wo.setExecutor("8888");//自动化助手，默认指定用户
                    wo.setExecuteTime(new Date());
                    JpaUtil.save(wo);

                    WarehouseOrderLine line = new WarehouseOrderLine();
                    line.setWhCode(wo.getWhCode());
                    line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    line.setItemCode(item.getItemCode());
                    line.setItemGroupCode(item.getItemGroupCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                    line.setQuantity(bill.getUnqualifiedQuantity());//不合格数量
                    line.setBizNo(wo.getBizNo());
                    line.setLineNo("1");
                    line.setOriginBizNo(inventoryQualityOrderLine.getOriginBizNo());
                    line.setOriginBizLineNo(inventoryQualityOrderLine.getOriginBizLineNo());
                    //记录新批次号
                    Lot lot = new Lot();
                    lot.setLotNo(lotNo);
                    lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());//索引
                    String binaryString = LotStatusUtil.toBinaryString("0");//默认正常
                    lot.setLotStatus(LotStatusUtil.switchBinaryByIndex(binaryString,InspectionEnums.LotStatusBitIndex.IB15.getIndex()));
                    lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                    JpaUtil.save(lot);

                    line.setSort("1");
                    line.setLotNo(lot.getLotNo());
                    line.setSubLotIndex(lot.getSubLotIndex());
                    line.setOriginNoticeNo(originNoticeNo);
                    line.setOriginNoticeLineNo(originNoticeLineNo);
                    JpaUtil.save(line);

                    //自动执行，生成流水
                    InvFlow inFlow = new InvFlow();
                    inFlow.setAccessType(wo.getAccessType());
                    inFlow.setItemCode(line.getItemCode());
                    inFlow.setWhCode(wo.getWhCode());
                    inFlow.setQuantity(line.getQuantity());
                    inFlow.setMemo(wo.getMemo());
                    inFlow.setOriginBizNo(wo.getOriginBizNo());
                    inFlow.setOriginBizType(wo.getOriginBizType());
                    inFlow.setOriginBizLineNo(line.getOriginBizLineNo());
                    inFlow.setWoBizNo(wo.getBizNo());
                    inFlow.setWoBizType(wo.getWoType());
                    inFlow.setWoBizLineNo(line.getLineNo());
                    inFlow.setLotNo(line.getLotNo());
                    inFlow.setSubLotIndex(line.getSubLotIndex());//增加子批索引
                    JpaUtil.save(inFlow);
                    //unqualifiedFlowList.add(inFlow);//不合格拆批明细*/
                    }
                }else{
                    testUnqualified = true;
                }
            }else if (originBizType.equals(InspectionEnums.OriginBizType.SALERE.getCode())){//销售退货入库验收 SoInQualityOrder
                SoInQualityOrder inQualityOrder = JpaUtil.getOne(SoInQualityOrder.class, originNoticeNo);
                SoInQualityOrderLine inQualityOrderLine = JpaUtil.getOne(SoInQualityOrderLine.class, lineKey);

                inQualityOrderLine.setAcceptanceBy(bill.getCreateBy());
                inQualityOrderLine.setAcceptanceTime(new Date());
                inQualityOrderLine.setCheckQuantity(bill.getCheckQuantity());
                inQualityOrderLine.setUnqualifiedQuantity(bill.getUnqualifiedQuantity());
                inQualityOrderLine.setConcessionQuantity(bill.getConcessionQuantity());
                inQualityOrderLine.setCheckResult(testResult);
                JpaUtil.update(inQualityOrderLine);//回写 验收单明细行 对应字段
                String lotNo = inQualityOrderLine.getLotNo();
                if (StringUtils.equals(testResult, TEST_RESULT_QUALIFIED)) {
                    if (bill.getReceiveQuantity()!=null&&bill.getReceiveQuantity().compareTo(BigDecimal.ZERO)!=0){
                        //接收数量生成对应仓单
                        WarehouseOrder inWo = new WarehouseOrder();
                        inWo.setAccessType(inQualityOrder.getAccessType());//入库
                        inWo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                        inWo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        inWo.setOrderStatus(OrderStatusEnums.OrderStatus.PLAN.getStatusCode());
                        inWo.setOrderDate(new Date());
                        inWo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        inWo.setWhCode(inQualityOrder.getWhCode());
                        inWo.setWoType(inQualityOrder.getPickingType());
                        inWo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                        JpaUtil.save(inWo);

                        WarehouseOrderLine inWoLine = new WarehouseOrderLine();
                        inWoLine.setWhCode(inWo.getWhCode());
                        inWoLine.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                        Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                        inWoLine.setItemCode(item.getItemCode());
                        inWoLine.setItemGroupCode(item.getItemGroupCode());
                        inWoLine.setItemName(item.getItemName());
                        inWoLine.setItemSpec(item.getItemSpec());
                        inWoLine.setUnitCode(item.getUnitCode());
                        inWoLine.setDrawingNo(item.getDrawingNo());
                        inWoLine.setQuantity(bill.getReceiveQuantity());//接收数量
                        inWoLine.setBizNo(inWo.getBizNo());
                        inWoLine.setLineNo("1");
                        inWoLine.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                        inWoLine.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                        inWoLine.setSort("1");

                        //此处生成新批次的原因在于批属性质检单单号字段记录质检单单号，批次库存视图会根据批次号关联质检单单号，获取质检情况数据，防止一个（批次+索引）对应多个质检单的情况
                        Lot lot = new Lot();
                        lot.setLotNo(lotNo);
                        lot.setLotStatus(LotStatusUtil.toBinaryString("0"));
                        lot.setSubLotIndex(lotService.getCountByLotNo(lotNo).toString());
                        lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                        JpaUtil.save(lot);
                        //退货时需要按批次退，故可以直接从验收单明细行中取值
                        inWoLine.setLotNo(lot.getLotNo());
                        inWoLine.setSubLotIndex(lot.getSubLotIndex());

                        inWoLine.setOriginNoticeNo(originNoticeNo);
                        inWoLine.setOriginNoticeLineNo(originNoticeLineNo);
                        JpaUtil.save(inWoLine);
                    }

                    if (bill.getUnqualifiedQuantity()!=null&&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0){
                        testQualifiedWithDefect = true;
                    /*//不合格数量 生成对应仓单 并自动执行
                    WarehouseOrder wo = new WarehouseOrder();
                    wo.setAccessType(inQualityOrder.getAccessType());//入库
                    wo.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    wo.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    wo.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());
                    wo.setOrderDate(new Date());
                    wo.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    wo.setWhCode("WH0005");// 仓单仓库 指定为不合格品仓：WH0005
                    wo.setWoType(inQualityOrder.getPickingType());
                    wo.setOriginNoticeNo(inQualityOrder.getNoticeNo());//关联noticeno字段
                    wo.setExecutor("8888");//自动化助手，默认指定用户
                    wo.setExecuteTime(new Date());
                    JpaUtil.save(wo);

                    WarehouseOrderLine line = new WarehouseOrderLine();
                    line.setWhCode(wo.getWhCode());
                    line.setCloseStatus(OrderStatusEnums.CloseStatus.OPEN.getStatusCode());
                    Item item = JpaUtil.linq(Item.class).idEqual(bill.getItemCode()).findOne();
                    line.setItemCode(item.getItemCode());
                    line.setItemGroupCode(item.getItemGroupCode());
                    line.setItemName(item.getItemName());
                    line.setItemSpec(item.getItemSpec());
                    line.setUnitCode(item.getUnitCode());
                    line.setDrawingNo(item.getDrawingNo());
                    line.setQuantity(bill.getUnqualifiedQuantity());//不合格数量
                    line.setBizNo(wo.getBizNo());
                    line.setLineNo("1");
                    line.setOriginBizNo(inQualityOrderLine.getOriginBizNo());
                    line.setOriginBizLineNo(inQualityOrderLine.getOriginBizLineNo());
                    line.setSort("1");

                    Lot lot = new Lot();
                    lot.setLotNo(inQualityOrderLine.getLotNo());
                    lot.setSubLotIndex(lotService.getCountByLotNo(inQualityOrderLine.getLotNo()).toString());//索引
                    String binaryString = LotStatusUtil.toBinaryString("0");//默认正常
                    lot.setLotStatus(LotStatusUtil.switchBinaryByIndex(binaryString,InspectionEnums.LotStatusBitIndex.IB15.getIndex()));
                    lot.setInspectionBillNo(bill.getBizNo());//不合格品批次生成时记录对应的质检单单号 溯源
                    JpaUtil.save(lot);

                    line.setLotNo(lot.getLotNo());
                    line.setSubLotIndex(lot.getSubLotIndex());
                    line.setOriginNoticeNo(originNoticeNo);
                    line.setOriginNoticeLineNo(originNoticeLineNo);
                    JpaUtil.save(line);

                    //自动执行，生成流水
                    InvFlow inFlow = new InvFlow();
                    inFlow.setAccessType(wo.getAccessType());
                    inFlow.setItemCode(line.getItemCode());
                    inFlow.setWhCode(wo.getWhCode());
                    inFlow.setQuantity(line.getQuantity());
                    inFlow.setMemo(wo.getMemo());
                    inFlow.setOriginBizNo(wo.getOriginBizNo());
                    inFlow.setOriginBizType(wo.getOriginBizType());
                    inFlow.setOriginBizLineNo(line.getOriginBizLineNo());
                    inFlow.setWoBizNo(wo.getBizNo());
                    inFlow.setWoBizType(wo.getWoType());
                    inFlow.setWoBizLineNo(line.getLineNo());
                    inFlow.setLotNo(line.getLotNo());
                    inFlow.setSubLotIndex(line.getSubLotIndex());//增加子批索引
                    JpaUtil.save(inFlow);
                    //unqualifiedFlowList.add(inFlow);//不合格拆批明细*/
                    }
                }else{
                    testUnqualified = true;
                }
            }else{
                return Result.error("来源单类型信息有误，无法关联对应的验收单！！！");
            }

            JpaUtil.linu(InspectionBill.class)
                    //.set("testResult", testResult)
                    .set("checkStatus", InspectionEnums.CheckStatus.FINISH.getCode())
                    .set("inspectionFinishTime",new Date())
                    .equal("bizNo",bill.getBizNo()).update();//更新质检单状态和检验完成时间

            if (originBizType.equals(InspectionEnums.OriginBizType.INVENTORY.getCode())) {//库存质检验收 代码放此处，是为了防止inspectbill状态未更新，产生计划数量
                //处理回写
                if (bill.getUnqualifiedQuantity()!=null
                        &&bill.getUnqualifiedQuantity().compareTo(BigDecimal.ZERO)!=0
                        &&bill.getUnqualifiedQuantity().compareTo(bill.getCheckQuantity())==0){
                    //考虑回写库存质检申请单单据状态（质检单完全不合格的情况）
                    InventoryInspectApply inspectApply = JpaUtil.getOne(InventoryInspectApply.class, bill.getOriginBizNo());
                    if (inspectApply!=null){
                        boolean orderCompletionFlag = true;//库存检验申请是否执行完成
                        List<InventoryInspectApplyLine> scrapOutApplyLines = JpaUtil.linq(InventoryInspectApplyLine.class).equal("bizNo", inspectApply.getBizNo()).list();
                        if (scrapOutApplyLines.size()>0){
                            NoticeClassVo scrapOutNoticeClazz = new NoticeClassVo(InventoryQualityOrder.class, InventoryQualityOrderLine.class);
                            List<NoticeClassVo> noticeClassVos = new ArrayList<NoticeClassVo>();
                            noticeClassVos.add(scrapOutNoticeClazz);
                            bizOrderLineService.handleBizOrderLineQuantity(scrapOutApplyLines, noticeClassVos, OrderEnums.AccessType.IN.getCode());

                            for (InventoryInspectApplyLine salesOrderLine:scrapOutApplyLines){
                                BigDecimal quantity = salesOrderLine.getQuantity();//订单行数量
                                BigDecimal actualQuantity = salesOrderLine.getActualQuantity();//已执行数量
                                //BigDecimal actualRejectQuantity = salesOrderLine.getActualRejectQuantity();//此部分为自动出数量
                                BigDecimal planQuantity = salesOrderLine.getPlanQuantity();//计划执行数量
                                BigDecimal planRejectQuantity = salesOrderLine.getPlanRejectQuantity();//由于是自动出，故此 计划退货数量为零
                                //判断订单行是否执行完成：1计划数量等于零，2已执行数量等于订单行数量
                                if (planQuantity.compareTo(BigDecimal.ZERO)!=0
                                        //||planRejectQuantity.compareTo(BigDecimal.ZERO)!=0
                                        ||quantity.compareTo(actualQuantity)!=0){
                                    orderCompletionFlag = false;
                                    break;
                                }
                            }
                            if (orderCompletionFlag){
                                inspectApply.setOrderStatus(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode());//完成
                                inspectApply.setExecuteTime(new Date());
                                JpaUtil.update(inspectApply);
                            }
                        }
                    }
                }
            }
            //有不合格的拆批入流水，自动生成对应的不良品处理单
            if (testQualifiedWithDefect){
                generateUnqualifiedDisposal(bill,bill.getUnqualifiedQuantity());
            }
            if (testUnqualified){
                generateUnqualifiedDisposal(bill,bill.getQuantity());
                //更新不合格数量为送检数量，接收（合格）数量为零
                JpaUtil.linu(InspectionBill.class)
                        .set("unqualifiedQuantity", bill.getQuantity())
                        .set("receiveQuantity",BigDecimal.ZERO)
                        .equal("bizNo",bill.getBizNo()).update();
                //更新验收单的不合格数量
                JpaUtil.linu(QualityUtils.getQualityOrderLineClass(originBizType))
                        .equal("noticeNo",bill.getOriginNoticeNo())
                        .equal("lineNo",bill.getOriginNoticeLineNo())
                        .set("unqualifiedQuantity",bill.getQuantity()).update();

            }
        }else if (StringUtils.equals(InspectionEnums.ISBusiType.Process.getCode(),busiType)){//制程质检
            if (StringUtils.isNotBlank(bill.getOriginWorkOrderTaskCode())){//工单工序任务对应质检单
                //更新task上checkingflag，更新task状态为已完成，更新order的工序指针
                ManufactureWorkOrderTask workOrderTask = JpaUtil.getOne(ManufactureWorkOrderTask.class, bill.getOriginWorkOrderTaskCode());
                if (workOrderTask==null){
                    throw new MBootException("数据异常，未能匹配到工单工序任务数据！");
                }
                workOrderTask.setInspectionBillChecking(CommonEnums.YesNo.NO.getCode());
                workOrderTask.setTaskStatus(MesEnums.WorkOrderTaskStatus.FINISH.getCode());//更新工序任务状态
                //todo 数量如何回写
                //workOrderTask.setScrapNum(bill.getScrapQuantity().intValue());
                //更新工单工序任务状态
                JpaUtil.update(workOrderTask);

                //更新工单工序任务指针
                ManufactureWorkOrder workOrder = JpaUtil.getOne(ManufactureWorkOrder.class, workOrderTask.getBatchCode());
                Integer nextProcOrder = workOrder.getNextProcOrder();
                List<ManufactureOrderRoute> routeList = manufactureOrderRouteService.list(workOrderTask.getBizNo());
                ManufactureOrderRoute orderNextProcRoute = MesScanUtil.getOrderNextProcRoute(routeList, nextProcOrder);
                workOrder.setNextProcOrder(orderNextProcRoute.getProcessOrder());
                JpaUtil.update(workOrder);

                //记录扫描info日志
                MesScanInfo mesScanInfo = new MesScanInfo(workOrderTask);
                JpaUtil.save(mesScanInfo);
            }else if (StringUtils.isNotBlank(bill.getOriginWorkOrderCode())){//首检批完工产品检验质检单
                //更新checkingflag、工单状态
                ManufactureWorkOrder workOrder = JpaUtil.getOne(ManufactureWorkOrder.class, bill.getOriginWorkOrderCode());
                workOrder.setInspectionBillChecking(CommonEnums.YesNo.NO.getCode());
                workOrder.setBatchStatus(MesEnums.WorkOrderStatus.FINISH.getCode());
                //todo 更新数量字段
                //workOrder.setBatchCompNum(bill.getQuantity().intValue());
                //workOrder.setBatchScrapNum(bill.getScrapQuantity().intValue());
                JpaUtil.update(workOrder);
            }
            JpaUtil.linu(InspectionBill.class)
                    //.set("testResult", testResult)
                    .set("checkStatus", InspectionEnums.CheckStatus.FINISH.getCode())
                    .set("inspectionFinishTime",new Date())
                    .equal("bizNo",bill.getBizNo()).update();//更新质检单状态和检验完成时间

        }else{
            return Result.error("不支持业务类型的质检单！");
        }

        return Result.OK("操作成功",bill);
    }

    @Override
    @Transactional
    public Result<List<InspectionBill>> listByNos(String bizNos) {
        List<InspectionBill> inspectionBills = JpaUtil.linq(InspectionBill.class).in("bizNo", Stream.of(bizNos.split(",")).collect(Collectors.toList())).list();
        return Result.OK(inspectionBills);
    }
    private void generateUnqualifiedDisposal(InspectionBill inspectionBill,BigDecimal applyQuantity){
        UnqualifiedDisposal unqualifiedDisposal = new UnqualifiedDisposal();
        unqualifiedDisposal.setApplyReason("质检单触发产生");
        unqualifiedDisposal.setBpmnStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        unqualifiedDisposal.setCrudType(CrudType.SAVE);
        unqualifiedDisposal.setSubmitTime(new Date());
        unqualifiedDisposal.setInspectionBillNo(inspectionBill.getBizNo());
        unqualifiedDisposal.setOriginBizType(inspectionBill.getOriginBizType());//记录源单类型，以便发起不同的工作流
        JpaUtil.save(unqualifiedDisposal);

        UnqualifiedDisposalLine line = new UnqualifiedDisposalLine();
        line.setLineNo("1");
        if(StringUtils.equals(inspectionBill.getOriginBizType(),InspectionEnums.OriginBizType.PURCH.getCode())
                ||StringUtils.equals(inspectionBill.getOriginBizType(),InspectionEnums.OriginBizType.OUTS.getCode())){
            line.setApplyDecision(InspectionEnums.UsageDecision.REJ.getCode());//采购、委外（外部的）默认判断
        }else{
            line.setApplyDecision(InspectionEnums.UsageDecision.REC.getCode());//其他默认让步接收
        }
        line.setApplyQuantity(applyQuantity);
        line.setInspectionBillNo(inspectionBill.getBizNo());
        line.setBizNo(unqualifiedDisposal.getBizNo());
        JpaUtil.save(line);

        //是否自动发起工作流
        if (UD_PROCESS_AUTOMATIC){
            Map<String, Object> properties = new HashMap<>();
            properties.putIfAbsent(CamundaConstant.BPMN_SORT_FLAG, "0");
            properties.put("businessKey",unqualifiedDisposal.getBizNo());
            properties.put("applyReason", unqualifiedDisposal.getApplyReason());
            properties.put("bizNo", unqualifiedDisposal.getBizNo());
            properties.put("bpmnStatus", unqualifiedDisposal.getBpmnStatus());
            properties.put("createBy", unqualifiedDisposal.getCreateBy());
            properties.put("createTime", unqualifiedDisposal.getCreateTime());
            properties.put("createDept", unqualifiedDisposal.getCreateDept());
            properties.put("inspectionBillNo", unqualifiedDisposal.getInspectionBillNo());
            properties.put("typeCode", unqualifiedDisposal.getTypeCode());
            properties.put("originBizType",unqualifiedDisposal.getOriginBizType());

            ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(UD_PROCESS_KEY, SecurityUtils.getLoginUsername(), unqualifiedDisposal.getBizNo(), properties);

            unqualifiedDisposal.setProcessInstanceId(processInstance.getId());
            unqualifiedDisposal.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode());
            JpaUtil.update(unqualifiedDisposal);//更新字段
        }
    }
}
